package com.kaifamiao.typehandler;

import com.kaifamiao.enums.Gender;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class GenderTypeHandler extends BaseTypeHandler<Gender> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int index, Gender gender, JdbcType jdbcType) throws SQLException {
        ps.setString(index, gender == null ? "UNKNOWN" : gender.name() );
    }

    @Override
    public Gender getNullableResult(ResultSet rs, String label) throws SQLException {
        String enumName = rs.getString(label);
        return enumName == null || enumName.trim().isEmpty() ? Gender.UNKNOWN : Gender.valueOf(enumName.toUpperCase());
    }

    @Override
    public Gender getNullableResult(ResultSet rs, int index) throws SQLException {
        String enumName = rs.getString(index);
        return enumName == null || enumName.trim().isEmpty() ? Gender.UNKNOWN : Gender.valueOf(enumName.toUpperCase());
    }

    @Override
    public Gender getNullableResult(CallableStatement cs, int index) throws SQLException {
        String enumName = cs.getString(index);
        return enumName == null || enumName.trim().isEmpty() ? Gender.UNKNOWN : Gender.valueOf(enumName.toUpperCase());
    }
}
